package com.hb.znpt.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.hb.znpt.BuildConfig;
import com.hb.znpt.bean.OssToken;
import com.unitlib.base.utils.SPUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Date;

public class STSGetter extends OSSFederationCredentialProvider {

    private static final String TAG = "STSGetter";

    @Override
    public OSSFederationToken getFederationToken() throws ClientException {
        OSSFederationToken authToken;
        long t = new Date().getTime();
        String json = "{\"bb\":\"" + BuildConfig.VERSION_CODE +
                "\",\"sfz\":\"" + SPUtils.getInstance().getString(Constants.SP_USERCARD) +
                "\",\"timestamp\":" + t + "}";
        String encrypt = null;
        try {
            encrypt = AESHttpUtil.加密(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String data = "{\"encrypt\":\"" + encrypt + "\",\"timestamp\":" + t + "}";

        try {
            //创建连接
            URL url = new URL(Constants.baseUrl + "/getToken");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            // POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(data);
            out.flush();
            out.close();
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
//                lines = URLDecoder.decode(lines, "utf-8");
                sb.append(lines);
            }
            LogUtils.json(TAG, sb.toString());

            OssToken token = JSON.parseObject(sb.toString(), OssToken.class);
            if (token.getReturn_code().equals("000000")) {
                String ak = token.getData().getAccesskeyid();
                String sk = token.getData().getAccesskeysecret();
                String to = token.getData().getSecuritytoken();
                String expiration = token.getData().getExpiration();
                authToken = new OSSFederationToken(ak, sk, to, expiration);
            } else {
                throw new ClientException("ErrorCode: " + token.getReturn_code() + "| ErrorMessage: " + token.getReturn_message());
            }
            reader.close();
            // 断开连接
            connection.disconnect();
            return authToken;
        } catch (Exception e) {
            throw new ClientException(e);
        }
    }
}
